Scala program to create a custom exception

Here, we are going to learn how to create a custom exception in Scala programming language?
Submitted by Nidhi, on June 08, 2021 [Last updated : March 12, 2023]

Scala - Creating Custom Exception

Here, we will create a custom exception class by extending the Exception class and declared the method with the throws keyword.

Scala code to create a custom exception

The source code to create a custom exception is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to create a custom exception

class MyException(msg: String) extends Exception(msg) {}
class ExceptionEx {
  @throws(classOf[MyException])
  def divide(num1: Int, num2: Int) {
    var result: Int = 0;
    if (num1 == 0) {
      throw new MyException("Divide by 0")
    } else {
      result = (num2 / num1);
      printf("Result: %d\n", result);
    }
  }
}

object Sample {
  // Main method
  def main(args: Array[String]) {
    try {
      var obj = new ExceptionEx();
      obj.divide(0, 10);
    } catch {
      case e: MyException => println(e);
    } finally {
      println("Finally block executed")
    }
  }
}

Output

MyException: Divide by 0
Finally block executed

Explanation

Here, we created a MyException class by extending the Exception class and then created a class ExceptionEx class, that contains the divide() method, created with the throws keyword.

And, we created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.

In the main() function, we created object of ExceptionEx class and called divide() method. And, we also defined catch and finally blocks to handle generated exceptions and print appropriate messages on the console screen.

Scala Exception Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.